from dwebsocket.decorators import accept_websocket

from utils.websocket import handle_request
from web_operation.selenium import run_use_case
from utils.selenium.perform import WPerform


def run_use_cases(perform: WPerform, use_cases):
    for use_case in use_cases:
        # 设置用例名称
        err_is_pass = use_case.get('err_is_pass', False)
        try:
            use_case_name = use_case.get('name')
            perform.send_msg('用例【%s】开始执行' % use_case_name)
            run_use_case(perform, use_case)
            perform.send_msg('用例【%s】执行完成' % use_case_name)
        except AttributeError as e:
            perform.send_err('属性未找到 ==> %s' % str(e), err_is_pass)
        except KeyError as e:
            perform.send_err('字段 %s 未找到' % str(e), err_is_pass)
        except Exception as e:
            print(e)
            perform.send_err(str(e), err_is_pass)
    perform.end()


def receive_func(receive_dic: dict, websocket):
    command = receive_dic.get('command')
    if command == 'run':
        data: dict = receive_dic.get('data')
        chrome: str = data.get('chrome')
        """执行用例数组"""
        perform = WPerform(websocket, chrome)
        group = data.get('group', False)
        # 判断是不是用例组
        if group:
            name = data.get('name')
            perform.send_msg('用例组【%s】开始执行' % name)
            run_use_cases(perform, data.get('use_cases'))
            perform.send_msg('用例组【%s】执行完成' % name)
        else:
            run_use_cases(perform, [data])
        perform.quit()


@accept_websocket
def AutoTest(request):
    handle_request(request, receive_func)


